using System;
using System.ComponentModel;
using System.Collections;
using System.Web.UI.WebControls;
using CommunityServer;
using CommunityServer.Controls;
using System.Collections.Specialized;

namespace FourRoads.Links.Controls
{
	/// <summary>
	/// Summary description for MostPopular.
	/// </summary>
	public class MostPopular : ResLinkBaseTemplatedWebControl
	{
		#region Child Controls
		RepeaterPlusNone  _NewLinks = null;
		#endregion

		public MostPopular()
		{
			
		}

		protected override void AttachChildControls()
		{
			_NewLinks = FindControl("PopularLinksList") as RepeaterPlusNone;
			_NewLinks.ItemDataBound += new RepeaterItemEventHandler(_NewLinks_ItemDataBound);
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad (e);

			if (!Page.IsPostBack)
			{
				DataBind();
			}
		}

		public override void DataBind()
		{
			base.DataBind ();

			_NewLinks.DataSource = ResLinkSection.GetPopularLinks(Top , ThisSection.SectionID);
			_NewLinks.DataBind();
		}

		[DefaultValue(10)]
		public int Top
		{
			get
			{
				if (ViewState["Top"] == null)
				{
					AttributeCollection attributes = TypeDescriptor.GetProperties(this)["Top"].Attributes;
				
					DefaultValueAttribute defValue = (DefaultValueAttribute)attributes[typeof(DefaultValueAttribute)];

					ViewState["Top"] = defValue.Value;
				}
				return (int)ViewState["Top"];
			}
			set
			{
				ViewState["Top"] = value;
			}
		}

		[DefaultValue(true)]
		public bool LinkToCurrentSection
		{
			get
			{
				if (ViewState["LinkToCurrentSection"] == null)
				{
					ViewState["LinkToCurrentSection"] = true;
				}
				return (bool)ViewState["LinkToCurrentSection"];
			}
			set
			{
				ViewState["LinkToCurrentSection"] = value;
			}
		}

		[DefaultValue(30)]
		public int LinkMaxStringLength
		{
			get
			{
				if (ViewState["LinkMaxStringLength"] == null)
				{
					AttributeCollection attributes = TypeDescriptor.GetProperties(this)["LinkMaxStringLength"].Attributes;
				
					DefaultValueAttribute defValue = (DefaultValueAttribute)attributes[typeof(DefaultValueAttribute)];

					ViewState["LinkMaxStringLength"] = defValue.Value;
				}
				return (int)ViewState["LinkMaxStringLength"];
			}
			set
			{
				ViewState["LinkMaxStringLength"] = value;
			}
		}

		private void _NewLinks_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if (e.Item.ItemType == ListItemType.Item || 
				e.Item.ItemType == ListItemType.AlternatingItem )
			{
				HyperLink hyp = e.Item.FindControl("PopularLink") as HyperLink;

				ResLinkLink lnk = e.Item.DataItem as ResLinkLink;

				if (lnk.Subject.Length > LinkMaxStringLength)
					hyp.Text = lnk.Subject.Substring(0 ,  LinkMaxStringLength) + "..";
				else
					hyp.Text = lnk.Subject;

				hyp.NavigateUrl = ResLinkUrls.Instance().ViewLink(lnk.SectionID , lnk.PostID);
			}
		}
	}
}
